<template>
	<jk-dialog
		v-model="showDialog"
		:title="`选择-机台`"
		width="800px"
		append-to-body
		@on-visible-change="onVisibleChange"
		@on-cancel="onVisibleChange(false)"
		@on-confirm="onConfirmBtn"
	>
		<header ref="box1" class="margin-bottom-4 flex-between-center">
			<div></div>
			<div class="flex-end-center">
				<jk-select v-model="searchParams.workshopId" :option-list="workshopList" clearable placeholder="区域" size="small" class="search-bar-item-size2 item-gap"></jk-select>
				<jk-select v-model="searchParams.processId" :option-list="processList" placeholder="工序" clearable size="small" class="search-bar-item-size1 item-gap"></jk-select>
				<jk-search-input v-model="searchParams.nameOrCode" class="search-bar-item-size2 item-gap" placeholder="编号或名称" @on-search="onSearchBtn"></jk-search-input>
				<jk-search-button size="small" @click="onSearchBtn"></jk-search-button>
			</div>
		</header>
		<div ref="box2" class="legend-container">
			<div
				v-for="(item, index) in legendList"
				:key="index"
				class="legend-item"
			>
				<div :style="{ background: item.bgColor }" class="legend-item-icon"></div>
				<div>{{ item.text }}</div>
			</div>
		</div>
		<jk-table
			ref="jkTable"
			:radio-config="{trigger: 'row'}"
			:loading="tableLoading"
			class="width-100-percent"
			:data="tableData"
			border
			highlight-hover-row
			highlight-current-row
			:row-style="rowClassName"
			:height="dialogTableHeight - 40"
			:checkbox-config="{checkMethod: checkboxMethod}"
			@checkbox-change="selectChangeEvent"
		>
			<vxe-column type="checkbox" width="60" align="center"></vxe-column>
			<vxe-column title="设备编码" align="left" field="code" :min-width="100" />
			<vxe-column title="设备名称" align="left" field="name" :min-width="100" />
			<vxe-column title="设备类型" align="center" field="typeName" :width="100" />
			<vxe-column title="设备机型" align="center" field="machineModelName" :min-width="100" />
			<vxe-column title="工序" align="center" field="processName" :width="100" />
			<vxe-column title="区域" align="left" field="workshopName" :width="100" />
		</jk-table>
		<footer ref="box3" class="flex-end-center margin-top-10">
			<jk-page
				:page-index="searchParams.pageNo"
				:page-sizes="searchParams.pageSizes"
				:page-size="searchParams.pageSize"
				:total="totalCount"
				layout="total, prev, pager, next"
				@on-change="onPageChange"
			/>
		</footer>
	</jk-dialog>
</template>

<script>
    import calDialogHeight from '../../../../mixins/cal-dialog-height';
    import { pageConfig, throttle } from '../../../../utils/jk/jk-tool';
    import { machinemanagerMachinePage } from '../../../../api/machine/machineArchives';
    import { spinProcessPage } from '../../../../api/technology/process';

    export default {
        mixins: [calDialogHeight],
        props: {
            dialogState: {
                type: Boolean,
                default: false
            },
            title: {
                type: String,
                default: ''
            },
            workshopId: {
                type: Number,
                default: null
            },
            scheduleShiftId: {
                type: Number,
                default: null
            },
            checkKeyName: {
                type: String,
                default: 'id'
            },
            defaultProcessName: {
                type: String,
                default: ''
            },
            defaultSelectRows: {
                type: Array,
                default() {
                    return [];
                }
            }
        },
        data() {
            return {
                totalCount: 0,
                searchParams: {
                    pageNo: pageConfig.pageNo,
                    pageSize: pageConfig.pageSize,
                    processId: null,
                    workshopId: null,
                    name: null,
                    scheduleShiftId: null,
                    nameOrCode: '',
                    auditState: 1,
                    ifScheduling: true
                },
                legendList: [
                    { count: 0, text: '0人', bgColor: '#c5c8ce' },
                    { count: 1, text: '1人', bgColor: '#19be6b' },
                    { count: 2, text: '2人', bgColor: '#2d8cf0' },
                    { count: 3, text: '3人', bgColor: '#ff9900' },
                    { count: 4, text: '4人及以上', bgColor: '#ed4014' }
                ],
                workshopList: [],
                processList: [],
                checkArr: [],
                selectRow: null,
                searchBarProcessId: null,
                tableData: [],
                showDialog: false,
                tableLoading: false,
                selectData: []
            };
        },
        methods: {
            rowClassName({ row, column }) {
                let color = '';
                if (!row.scheduleEmpCount) {
                    color = this.legendList.find(x => x.count === 0).bgColor;
                } else if (row.scheduleEmpCount > 3) {
                    color = this.legendList.find(x => x.count === 4).bgColor;
                } else {
                    color = this.legendList.find(x => x.count === row.scheduleEmpCount).bgColor;
                }
                return {
                    color: '#fff',
                    background: color
                };
            },
            selectChangeEvent({ records }) {
                this.checkArr = records.filter(x => !x._disabled).map(x => {
                    return x;
                });
            },
            checkboxMethod(e) {
                return !e.row._disabled;
            },
            onSearchBtn() {
                this.$set(this.searchParams, 'pageNo', 1);
                this.getListRequest();
            },
            onPageChange(e, size) {
                this.$set(this.searchParams, 'pageNo', e);
                this.$set(this.searchParams, 'pageSize', size);
                this.getListRequest();
            },
            onConfirmBtn: throttle((e, _this) => {
                if (_this.checkArr.length) {
                    const arr = _this.checkArr.filter(x => !x._disabled);
                    _this.$emit('on-confirm', arr);
                } else {
                    _this.$tipsBar(_this, 'custom', 'warning', '请选择数据');
                }
            }, 1000),
            setCheckState(arr) {
                arr.forEach((x) => {
                    x._disabled = false;
                    this.defaultSelectRows.forEach(k => {
                        if (x.id === k[this.checkKeyName]) {
                            x._disabled = true;
                        }
                    });
                });
                this.tableData = arr;
                this.tableData.forEach((x, index) => {
                    if (x._disabled) {
                        this.$refs.jkTable.$refs.xTable.setCheckboxRow([this.tableData[index], this.tableData[index]], true);
                    }
                });
            },
            getListRequest() {
                this.tableLoading = true;
                this.selectData = [];
                return machinemanagerMachinePage(this.searchParams).then(res => {
                    this.tableLoading = false;
                    if (res.data.status === 200) {
                        this.totalCount = res.data.count;
                        this.setCheckState(res.data.res || []);
                    }
                });
            },
            onVisibleChange(e) {
                this.$emit('on-visible-change', e);
                if (!e) {
                    Object.assign(this.$data, this.$options.data());
                }
            },
            getProcessListRequest() {
                return spinProcessPage().then(res => {
                    if (res.data.status === 200) {
                        this.processList = res.data.res;
                        if (this.defaultProcessName) {
                            const item = this.processList.find(x => x.name === this.defaultProcessName) || {};
                            this.$set(this.searchParams, 'processId', item.id);
                        }
                    }
                });
            },
            async getDependentData() {
                this.tableLoading = true;
                this.workshopList = this.$store.state.user.userWorkshop.workshopList;
                this.$set(this.searchParams, 'workshopId', this.workshopId || this.$store.state.user.userWorkshop.defaultWorkshopId);
                await this.getProcessListRequest();
                await this.getListRequest();
            }
        },
        watch: {
            dialogState(newVal) {
                this.showDialog = newVal;
                this.searchParams.scheduleShiftId = this.scheduleShiftId;
                if (newVal) {
                    this.getDependentData();
                }
            }
        }
    };
</script>
<style scoped lang="scss">
    $legend_icon_width: 24px;
    $legend_icon_height: 14px;
    $legend_height: 30px;

    .legend-container {
        height: $legend_height;
        display: flex;
        justify-content: center;
        align-items: center;
        padding: 0 0;
        box-sizing: border-box;
        .legend-item {
            display: flex;
            justify-content: center;
            align-items: center;
            margin:  0 10px;
            font-size: 12px;
            .legend-item-icon {
                width: $legend_icon_width;
                height: $legend_icon_height;
                margin-right: 4px;
                background: #e8eaec;
                border-radius: 2px;
            }
        }
    }
</style>
